const express = require('express')
const cartsRouter = express.Router()
const jwt = require('jwt-simple')
const cartsController = require('../controller/carts')
// 需要token  拦截 如果带了token 才能访问以下接口
// 前端需要发送 token 
cartsRouter.use((req, res, next) => {
    // 前端
    // 携带数据到后端的方式：
    console.log(req.url, req.body, req.params, req.query)
    const token = req.body.token || req.query.token || req.headers.token || (req.cookies && req.cookies.token) || ''
    console.log('token', token)
    if (token) {
        try {
            // 根据 tokenKey 解密token
            const result = jwt.decode(token, require('../config/index').tokenKey)
            if (result) {
                console.log('result', result.info)
                req.userInfo = result.info
                next()
            } else {
                res.json({
                    code: 500,
                    msg: 'token失效，请重新登录',
                    data: null
                })
            }
        } catch (error) {
            console.log(error)
            res.json({
                code: 1002,
                msg: 'token失效，请重新登录',
                data: null
            })
        }
    } else {
        res.json({
            code: '1001',
            msg: 'token为空，请重新登录',
            data: null
        })
    }
})




// 获取购物车信息
cartsRouter.get('/getCartsInfoByUser', cartsController.getCartsInfoByUser)
// 删除购物车
cartsRouter.post('/deleteCart', cartsController.deleteCarts)
// 添加购物车
cartsRouter.post('/addCarts', cartsController.addCarts)
// 修改购物车
cartsRouter.post('/editCartsNum', cartsController.editCartsNum)
// 结算
cartsRouter.post('/settleAccounts', cartsController.settleAccounts)

// 跟新购物车
cartsRouter.post('/updateCart', cartsController.updateCart)


module.exports = cartsRouter
